package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.DTO.common.AccessToken;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.words.AccessTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;

/**
* 缓存accessToken 微信第三方平台开发者交互凭证。
*
*@createDate 2019/05/17
*/
@Aspect
@Component
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {
    protected static final Logger LOG = LoggerFactory.getLogger(AccessTokenInterceptor.class);

    // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.wechat.*.*(..)) && !@annotation(com.itlong.cloud.annotation.UnAuthAccessRequired)")
    public void excudeService(){}

    @Value("${" + PlatformConstants.WECHAT_OFFICIAL_APPID + "}")
    private String appid;
    @Value("${" + PlatformConstants.WECHAT_OFFICIAL_SECRET + "}")
    private String appsecret;

    @Autowired
    RedisService redisService;


    /**
     * accessToken的微信服务器端有效期为2小时，设置同步缓存，将获取到的accessToken信息放入memcached
    */
    @Before("excudeService()")
    public Object twiceAsOld() throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            String accessToken=redisService.get(RedisConstant.WECHAT_OFFICIAL_ACCESS_TOKEN);
            if(request.getRequestURI().equals("/foreign/wechat/message") ||
                    request.getRequestURI().equals("/foreign/menu/createMenu")) {
                if (accessToken == null) {
                    //如果没有获得accessToken 那么创建一个accessToken
                    AccessToken token = AccessTokenUtil.getAccessToken(appid, appsecret);
                    if(token!=null && StringUtils.isNotBlank(token.getAccess_token())){
                        redisService.set(RedisConstant.WECHAT_OFFICIAL_ACCESS_TOKEN, RedisConstant.WECHAT_ACCESS_TOKEN_TOKEN_TIME,token.getAccess_token());
                    }
                }
            }
        }catch(Exception e){
            LOG.error("获取accessToken失败",e);
        }
        return true;
    }
}
